import { ref } from 'vue';

export default function useWebSocket(url: any) {
  const messagesData = ref([]);

  // 创建WebSocket连接和相关方法
  const socket = new WebSocket(url);

  socket.onopen = () => {
    console.log('WebSocket连接已建立');
  };

  socket.onmessage = (event) => {
    const receivedMessage = JSON.parse(event.data);
    // 接收到后端消息，根据业务逻辑自行处理
  };

  socket.onclose = () => {
    console.log('WebSocket连接已关闭');
  };
  return {
    messagesData,
    sendMessage: (message: any) => {
      if (socket.readyState === WebSocket.OPEN) {
        socket.send(message);
      }
    },
    closeConnection: () => {
      socket.close();
    },
  };
}
